package com.mojiayi.learn.sentinel.dubbo.provider;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.dubbo.config.annotation.Service;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.mojiayi.learn.common.result.ListResultSet;
import com.mojiayi.learn.common.result.ResultSet;
import com.mojiayi.learn.sentinel.stub.domain.dto.UserDetailDTO;
import com.mojiayi.learn.sentinel.stub.domain.params.UserDetailParams;
import com.mojiayi.learn.sentinel.stub.service.IUserProvider;

import java.util.Date;
import java.util.Random;

@Service(version = "1.0.0", owner = "liguangri")
public class UserProvider implements IUserProvider {
    @SentinelResource(value = "getUserDetailByPhone", fallback = "getUserDetailByPhoneFallback")
    @Override
    public ResultSet<UserDetailDTO> getUserDetailByPhone(UserDetailParams userDetailParams) {
        System.out.println("invoke getUserDetailByPhone successfully");
        Preconditions.checkArgument(!Strings.isNullOrEmpty(userDetailParams.getPhone()), "手机号不能为空");
        ResultSet<UserDetailDTO> resultSet = new ResultSet<>();
        UserDetailDTO userDetailDTO = mockUserDetailData(userDetailParams);
        resultSet.setResult(userDetailDTO);
        return resultSet;
    }

    @Override
    public ListResultSet<UserDetailDTO> qryUserDetailByRealName(UserDetailParams userDetailParams) {
        Preconditions.checkArgument(!Strings.isNullOrEmpty(userDetailParams.getRealName()), "真实姓名不能为空");
        ListResultSet<UserDetailDTO> listResultSet = new ListResultSet<>();
        for (int index = 0; index < 8; index++) {
            listResultSet.addResult(mockUserDetailData(userDetailParams));
        }
        return listResultSet;
    }

    private String getUserDetailByPhoneFallback(UserDetailParams userDetailParams, Throwable t) {
        t.printStackTrace();
        return "达到访问限制条件，phone=" + userDetailParams.getPhone();
    }

    private UserDetailDTO mockUserDetailData(UserDetailParams userDetailParams) {
        Random random = new Random();
        UserDetailDTO userDetailDTO = new UserDetailDTO();
        userDetailDTO.setUserId(Math.abs(random.nextLong()) * 10000);
        userDetailDTO.setNickname("nickname" + userDetailDTO.getUserId());
        userDetailDTO.setCreateTime(new Date());
        if (Strings.isNullOrEmpty(userDetailDTO.getPhone())) {
            userDetailDTO.setPhone("phone" + userDetailDTO.getUserId());
        } else {
            userDetailDTO.setPhone(userDetailParams.getPhone());
        }
        if (Strings.isNullOrEmpty(userDetailDTO.getRealName())) {
            userDetailDTO.setRealName("realName" + userDetailDTO.getUserId());
        } else {
            userDetailDTO.setRealName(userDetailParams.getRealName());
        }
        return userDetailDTO;
    }
}
